package com.template.project.controller;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Controller 相关的父类
 *
 * @author Admin
 */
@Slf4j
public abstract class BaseController {

    @Resource
    private HttpServletRequest httpServletRequest;

    @Resource
    private HttpServletResponse httpServletResponse;

    /**
     * 获取HttpServletRequest
     */
    public HttpServletRequest getHttpServletRequest() {
        try {
            return httpServletRequest;
        } catch (Exception e) {
            log.error("Error retrieving HttpServletRequest", e);
            return null;
        }
    }

    /**
     * 获取HttpServletResponse
     */
    public HttpServletResponse getHttpServletResponse() {
        try {
            return httpServletResponse;
        } catch (Exception e) {
            log.error("Error retrieving HttpServletResponse", e);
            return null;
        }
    }

    /**
     * 获取ServletRequestAttributes
     */
    private ServletRequestAttributes getRequestAttributes() {
        try {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes instanceof ServletRequestAttributes) {
                return (ServletRequestAttributes) requestAttributes;
            }
        } catch (Exception e) {
            log.error("Error retrieving ServletRequestAttributes", e);
        }
        return null;
    }
}
